-module(ring).
-export([start/1, send_msg/1, stop/0]).
-export([send/1, start_help/1, start_loop/0]).

start(N) -> call({start, N}).
send_msg(Msg) -> call({send_msg, Msg}).
stop() -> call(stop).

call({start, N}) ->
    spawn(?MODULE, start_help, [N]);
call({send_msg, Msg}) ->
    ring ! {ok, Msg};
call(stop) ->
    ring ! stop.

start_help(N) ->
    register(ring, create_processes(N, self())),
    start_loop().

start_loop() ->
    receive 
	{ok, Content} -> ring ! {ok, Content},
			 start_loop();
	stop -> ok
    end.

% 创建N,N-1,...,2进程，其中第N个进程指向当前进程Pid
% 当创建完第1个进程后，就接收消息，并返回该进程的Pid
create_processes(N, AfterPid) when N > 1->
    CurrPid = spawn(?MODULE, send, [AfterPid]),
    create_processes(N-1, CurrPid);
create_processes(1, AfterPid) ->
    spawn(?MODULE, send, [AfterPid]).

send(Pid) ->
    receive  
	{ok, Content} -> 
	    Pid ! {ok, Content},
	    io:format("Pid:~p, Msg:~p~n", [self(), Content]),
	    send(Pid);
	stop -> 
	    Pid ! stop
    end.
